package com.filesearcher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;


public class StringCompress {

	public static final byte[] compress(String str) throws IOException 
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ZipOutputStream zout = new ZipOutputStream(out);
		zout.putNextEntry(new ZipEntry("0"));
		zout.write(str.getBytes());
		zout.closeEntry();
		byte[] compressed = out.toByteArray();
		zout.close();
		
		return compressed;
	}

	public static final String decompress(byte[] compressed) throws IOException 
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(compressed);
		ZipInputStream zin = new ZipInputStream(in);
		zin.getNextEntry();
		byte[] buffer = new byte[1024];
		int offset = -1;
		
		while( (offset = zin.read(buffer) ) != -1 ) 
		{
			out.write( buffer, 0, offset );
		}
		
		String decompressed = out.toString();
				
		zin.closeEntry();		
		out.close();
		zin.close();
		
		return decompressed;
	}

	public static final void main(String[] args) 
	{
		String str = "Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n" +
		"Compress this string\r\n";
		
		try 
		{
			byte[] compressed = compress(str);
			int compressedSize = compressed.length;
			String decompressed = decompress(compressed);
			int decompressedSize = decompressed.getBytes().length;
			System.out.println("Compressed Size = " + compressedSize);
			System.out.println("Decompressed Size = " + decompressedSize);
		} 
		catch(IOException e) 
		{
			e.printStackTrace();
		}
	} 
}
